package com.pan.insist.controller.admin;

import com.pan.insist.base.BaseController;
import com.pan.insist.model.UserModel;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 控制层 -- 后台登录
 *
 * @author kaiji
 * @since 2019-08-15
 */
@Log4j2
@Controller
public class LoginController extends BaseController {

    @GetMapping("login")
    public String login(String error, ModelMap modelMap) {
        log.info("开始到现在~~~~");
        if (error != null) {
            modelMap.put("error", error);
        }
        return "login";
    }

    @PostMapping("toLogin")
    public String toLogin(UserModel userModel, boolean rememberMe, RedirectAttributes attr) {
        if (StringUtils.isBlank(userModel.getPhone())) {
            attr.addAttribute("error", "请输入手机号码！");
            return REDIRECT + "login";
        }
        if (StringUtils.isBlank(userModel.getAuthCode())) {
            attr.addAttribute("error", "请输入验证码！");
            return REDIRECT + "login";
        }

        UsernamePasswordToken token = new UsernamePasswordToken(userModel.getPhone(), userModel.getAuthCode());
        try {
            token.setRememberMe(rememberMe);
            SecurityUtils.getSubject().login(token);
        } catch (AccountException ae) {
            attr.addAttribute("error", ae.getMessage());
            return REDIRECT + "login";
        }
        return REDIRECT + "page";
    }

    @GetMapping("logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return REDIRECT + "login";
    }

    @GetMapping("/notRole")
    public Object notRole() {
        log.info("您没有权限， 权限不足！");
        return "notRole";
    }
}
